package com.face.gaoml.netlibrary.utils;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.face.gaoml.netlibrary.App;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Locale;



/**
 * 通用的变量和方法类
 */
public class Util {

    public static Drawable creatGrayBitmap(Bitmap paramBitmap) {
        Drawable localDrawable = null;
        if (paramBitmap != null) {
            Bitmap.Config localConfig = paramBitmap.getConfig();
            Paint localPaint = new Paint();
            ColorMatrix localColorMatrix = new ColorMatrix();
            localColorMatrix.setScale(0.8F, 0.8F, 0.8F, 1.0F);
            localPaint.setColorFilter(new ColorMatrixColorFilter(
                    localColorMatrix));
            if (localConfig == null)
                localConfig = Bitmap.Config.ARGB_8888;
            Bitmap localBitmap = Bitmap.createBitmap(paramBitmap.getWidth(),
                    paramBitmap.getHeight(), localConfig);
            new Canvas(localBitmap).drawBitmap(paramBitmap, 0.0F, 0.0F,
                    localPaint);
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.PNG, 100,
                    localByteArrayOutputStream);
            localDrawable = BitmapDrawable.createFromStream(
                    new ByteArrayInputStream(localByteArrayOutputStream
                            .toByteArray()), "ColorFilterRelativeLayout");
            paramBitmap.recycle();
            localBitmap.recycle();
        }
        return localDrawable;
    }

    /**
     * 根据变量名称获得变量值
     *
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    public static int getRValue(String name) {
        try {
            return android.R.drawable.class.getField(name).getInt(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftInputFromWindow(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    public static String getVersionName(Context context) {
        //	String packageName = "";
        String versionName = "";
        int versionCode = 0;
        PackageInfo packageInfo = null;
        try {    //取得包名
            String packageName = context.getPackageName();
            //取得包信息
            packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            versionCode = packageInfo.versionCode;
            versionName = packageInfo.versionName;
        } catch (Exception e) {
        }
        return versionName;
    }

    /**
     * 设置Button是否可以点击
     */
    public static void setButtonClickable(View view, boolean isChecked) {
        if (isChecked) {
            view.getBackground().setAlpha(255);//0~255透明度值
            view.setClickable(true);
        } else {
            view.getBackground().setAlpha(100);//0~255透明度值
            view.setClickable(false);
        }
    }

    public static String getSystemLanguage(Context mContext) {
        Locale locale = mContext.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        //     LogUtil.e("test", "language="+language);
        return language;
    }

    /**
     * 获取手机mac地址
     */
    public static String getLocalMacAddress(Context mContext) {
        WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**
     * 判断有无sim卡
     *
     * @param
     * @return true : sim存在<br/>
     * false: sim不存在
     */
    public static boolean isSimExist(Context mContext) {
        TelephonyManager manager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        int absent = manager.getSimState();
        if (1 == absent) {
            //   displayToast("请确认sim卡是否插入或者sim卡暂时不可用！");
            return false;
        } else {
            return true;
        }
    }

    private boolean isZh(Context mContext) {
        Locale locale = mContext.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh")) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取当前进程名
     *
     * @param context
     * @return 进程名
     */
    public static final String getProcessName(Context context) {
        String processName = null;

        // ActivityManager
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));

        while (true) {
            for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;
                    break;
                }
            }

            // go home
            if (!TextUtils.isEmpty(processName)) {
                return processName;
            }

            // take a rest and again
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * 检查当前网络是否可用
     *
     * @param
     * @return
     */


    public static  boolean isNetworkAvailable() {
        // = mApplication.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) App.appApplication.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    public static String GetNetworkType(Application appApplication) {
        String strNetworkType = "";

        NetworkInfo networkInfo = ((ConnectivityManager) appApplication.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();

                Log.e("cocos2d-x", "Network getSubtypeName : " + _strSubTypeName);

                // TD-SCDMA   networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }

                Log.e("cocos2d-x", "Network getSubtype : " + Integer.valueOf(networkType).toString());
            }
        }

        Log.e("cocos2d-x", "Network Type : " + strNetworkType);

        return strNetworkType;
    }

}